<template>
  <div class="page-main-card layout-padding layout-padding-auto">
    <el-card shadow="hover" class="mb10">
      <el-form :inline="true"  size="default">
        <el-form-item>
          <el-select  v-model="state.filter.type" placeholder=视图 clearable @change="changeType"
                      style="min-width: 140px;">
            <el-option label="默认展示" value="all"></el-option>
            <el-option label="只看图表" value="chart"></el-option>
            <el-option label="只看数据" value="data"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-date-picker  v-model="state.filter.range_day" type="daterange"
                           :clearable="false" :shortcuts="shortcutsDate" value-format="YYYY-MM-DD" range-separator="至" style="width: 240px;" />
        </el-form-item>
        <el-form-item>
          <el-select  v-model="state.filter.isMaster" placeholder=应用名 clearable filterable>
            <el-option label="主力" value="1"></el-option>
            <el-option label="所有" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select  v-model="state.filter.union_type" placeholder=应用名 clearable filterable
                      style="min-width: 140px;">
            <el-option label="全部交易所" value="all"></el-option>
            <el-option v-for="(v,k) in state.brandMap" :label="v" :value="k"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select  v-model="state.filter.pkg" placeholder=应用名 clearable filterable
                      style="min-width: 140px;">
            <el-option label="全部品种" value="all"></el-option>
            <el-option v-for="(v,k) in state.appMap" :label="v" :value="k"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item >
          <el-select  v-model="state.filter.q" placeholder=请选择合约 clearable filterable
                      style="min-width: 140px;">
            <el-option v-for="(v,k) in state.codeArrMap" :label="v" :value="v"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="search" size="default" type="primary">
            <el-icon>
              <ele-Search />
            </el-icon>
            查询
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="downTable" size="default">
            <el-icon>
              <ele-Download />
            </el-icon>
            下载excel
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="updateTable" size="default">
            所有初始化
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="updatePrice" size="default">
            更新价格
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="updateChiCang" size="default">
            更新持仓
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="solveTable" size="default">
            处理
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card shadow="hover"  class="layout-padding-auto" :key="state.filter.type" v-show="state.filter.type==='all'||state.filter.type==='chart'">
      <div ref="echartsMapRef"  style="min-height: 35vh;"></div>
    </el-card>
    <el-form :inline="true"  size="default" class="mb10" v-show="state.filter.type==='all'||state.filter.type==='data'">
      <el-checkbox
          v-for="v in state.tNames"
          v-model="v[3]"
          :label="v[0]"
          @change="changetNames(v)"
      />
    </el-form>
    <el-card shadow="hover" class="layout-padding-auto"  v-show="state.filter.type==='all'||state.filter.type==='data'">
      <el-table border @sortChange="sortChange" :data="state.tableData.list" v-loading="state.tableData.loading" style="width: 100%">
        <template v-for="(v,k) in state.tableData.tNames">
          <el-table-column v-if="v[1]==='code'" :sortable="v[2]" :prop="v[1]" :label="v[0]">
            <template #default="scope">
              <span style="color:#0256ff;cursor: pointer;" @click="tItemClick(scope.row,'code')">{{scope.row['code']}}</span>
            </template>
          </el-table-column>
          <el-table-column v-else :sortable="v[2]" :prop="v[1]" :label="v[0]" ></el-table-column>
        </template>

      </el-table>
      <el-pagination @size-change="onHandleSizeChange" @current-change="onHandleCurrentChange" class="mt15"
                     :pager-count="5" :page-sizes="[10, 20, 30]" v-model:current-page="state.filter.pageIndex" background
                     v-model:page-size="state.filter.pageSize" layout="total, sizes, prev, pager, next, jumper"
                     :total="state.showList.length">
      </el-pagination>
    </el-card>
  </div>
</template>

<script setup lang="ts" name="systemUser">
import { defineAsyncComponent, reactive, onMounted, computed,ref } from 'vue';
import { useRoute } from 'vue-router';
import dayjs from 'dayjs';
import router from '/@/router';
import {formatDate, shortcutsDate} from "/@/utils/formatTime";
import CacheRequest from "/@/utils/CacheRequest";
import request from "/@/utils/request";
import ExportJsonExcel from "js-export-excel";
import * as echarts from 'echarts';
const getData=async (data:object)=>{
  //缓存300秒
  return await CacheRequest(async function (){
    const res=await request({
      url: '/api/getData',
      method: 'post',
      data:data,
    })
    if(res.code===0){
      return res.data
    }else{
      throw res.msg
    }
  },JSON.stringify(data),600)
}
// 定义变量内容
const echartsMapRef = ref<RefType>('');
// 引入组件
const route = useRoute();
const tNames=[
  ['日期','day','custom',true,false,true],
  ['名称','title','custom',true,false],
  ['合约','code','custom',true,false],
  ['散户','sanhu','custom',true,false,false,true],
  ['机构','zhuli','custom',true,false,false,true],
  ['羊','a1','custom',true,false],
  ['狼','a2','custom',true,false],
  ['对抗','duikang','custom',true,false],
  ['散户对抗','sanhuduikang','custom',true,false],
  ['ar26','ar26','custom',true,false],
  ['br26','br26','custom',true,false],
  ['arbr差别','arbrdiff','custom',true,false],
  ['dj差别','djdiff','custom',true,false],
  ['k9','k9','custom',true,false],
  ['d9','d9','custom',true,false],
  ['j9','j9','custom',true,false],
  ['lv5','lv5','custom',true,false],
  ['lv10','lv10','custom',true,false],
  ['lv20','lv20','custom',true,false],

  ['昨收','preClose','custom',true,false,false,true],
  ['昨结算','zjsj','custom',true,false],
  ['开盘','open','custom',true,false],
  ['收盘','close','custom',true,false],
  ['最高','high','custom',true,false],
  ['最低','low','custom',true,false],
  ['成交量','volume','custom',true,false],
  ['成交额','cje','custom',true,false],
  ['涨跌额','zde','custom',true,false],
  ['涨跌幅','zdf','custom',true,false],
  ['持仓量','ccl','custom',true,false],
  ['外盘','waipan','custom',true,false],
  ['内盘','neipan','custom',true,false],

  ['ma5均价','ma5avgprice','custom',true,false],
  ['ma5成交量','ma5volume','custom',true,false],
  ['ma10均价','ma10avgprice','custom',true,false],
  ['ma10成交量','ma10volume','custom',true,false],
  ['ma20均价','ma20avgprice','custom',true,false],
  ['ma20成交量','ma20volume','custom',true,false],

]
const brandMap={

}
const routeQuery=Object.assign({},route.query)
if(routeQuery.range_day){
  routeQuery.range_day=routeQuery.range_day.split(',')
}
// 定义变量内容
const state = reactive({
  brandMap:Object.assign({},brandMap),
  codeArr:[],
  codeArrMap:[],
  tNames:tNames,
  tjList:[],
  listHeader:[],
  showHeader:[],
  tableData: {
    tNames: tNames,
    list: [],
    loading: false,
  },
  filter: {
    type: route.query.type||'all',
    pkg: route.query.pkg||'all',
    pageIndex: parseInt(route.query.pageIndex)||1,
    pageSize: parseInt(route.query.pageSize)||10,
    range_day:routeQuery.range_day||[formatDate(new Date(new Date().getTime()-86400000), 'yyyy-MM-dd'), formatDate(new Date(), 'yyyy-MM-dd')],
    q: route.query.q||'',
    isMaster: route.query.isMaster||'1',
    union_type:route.query.union_type||'all',//产商名
  },

  allList:[],
  showList:[],
  codeNames:[],

  appMap:{},//应用名
  apps:[],//app包名数据
});

const getOneDay=async function(){
  for(let i=0;i<state.codeArr.length;i++){
    const code=state.codeArr[i]
    const title=state.codeNames[i]
    try {
      const temp= await getData({
        range_day:state.filter.range_day.join(','),
        code:code,
        pkg:'qihuo',
        method:'getList'
      })
      temp.forEach(function(item){
        item.title=title
        item.code=code
        item.arbrdiff=parseInt(item.br26-item.ar26)
        item.djdiff=parseInt(item.j9-item.d9)
        const abs1=Math.abs(item.sanhu)
        const abs2=Math.abs(item.zhuli)
        const a1=parseInt(item.sanhu*100/(abs1+abs2))
        const a2=parseInt(item.zhuli*100/(abs1+abs2))
        item.a1=a1
        item.a2=a2
        if(a1>0&&a2<0||a1<0&&a2>0){
          item.duikang=100-Math.abs(a1+a2)
        }else{
          item.duikang=0
        }
        if(abs1>abs2&&a1>0&&a2<0||a1<0&&a2>0){
          item.sanhuduikang=100-Math.abs(a1+a2)
        }else{
          item.sanhuduikang=0
        }
        state.showList.push(item)
      })
    }catch (e){

    }

  }
}
const changeType=async ()=>{
  initTable()
}
// 初始化 echartsMap
const initEchartsMap = async (days) => {
  // 基于准备好的dom，初始化echarts实例
  var myChart = echarts.init(echartsMapRef.value);

  let option
  const series=[]
  const nameArr=[]
  const keyArr=[]
  const selected={}
  option = {
    "title": {
      "subtext": "",
      "left": "left"
    },
    yAxis: {
      type: 'value'
    },
    tooltip: {
      trigger: 'axis'
    },
    grid: {
      left: '0%',
      right: '0%',
      bottom: '0%',
      containLabel: true
    },
    toolbox: {
      feature: {
        saveAsImage: {}
      }
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: days
    },
    legend: {
      data: nameArr,
      selected: selected
    },
    "series": series
  }

  tNames.forEach(function(arr){
    if(arr[5]!==true){
      series.push({
        name: arr[0],
        type: 'line',
        stack: 'Total',
        data: []
      })
      keyArr.push(arr[1])
      nameArr.push(arr[0])
      selected[arr[0]]=arr[6]===true
    }
  })

  state.showList.forEach(function (item){
    keyArr.forEach(function (key,i){
      const nd=days.indexOf(item.day)
      if(!series[i].data[nd]){
        series[i].data[nd]=0
      }
      series[i].data[nd]+=item[key]||0
      series[i].data[nd]=parseInt((series[i].data[nd])*100)/100
    })
  })
  console.log(option)
// 绘制图表
  myChart.setOption(option);

};
// 初始化表格数据
const initTable=async ()=>{

  state.tableData.loading = true;
  const days=[]
  days.push(state.filter.range_day[0])
  const endTime=new Date(state.filter.range_day[1]+' 23:59:59').getTime()
  let curTime=new Date(state.filter.range_day[0]+' 01:00:00').getTime()+86400000
  while(curTime<endTime){
    days.push(formatDate(new Date(curTime), 'yyyy-MM-dd'))
    curTime=curTime+86400000
  }
  //请求总的列表数据
  state.allList=[]
  state.showList=[]

  await getOneDay()
  state.allList=state.showList
  state.tableData.loading = false;
  if(state.filter.type=='all'||state.filter.type==='chart'){
    await initEchartsMap(days)
  }
  if(state.filter.type=='all'||state.filter.type==='data') {
    await getTableData()
  }

}

const getTableData = async () => {
  state.tableData.loading = true;
  const start=(state.filter.pageIndex-1)*state.filter.pageSize
  const end=Math.min(start+state.filter.pageSize,state.showList.length)
  const list=[]
  for(let i=start;i<end;i++){
    const item=state.showList[i]
    if(!item.hasDetail){
      try {
        item.hasDetail=true
        // await getDetail(item)
      }catch (e){
        item.hasDetail=false
      }
    }
    list.push(item)
  }
  state.tableData.list = list

  state.tableData.loading = false;
};
//排序
const sortChange= async(item)=>{

  let d=1
  if(item.order==='ascending'){
    d=1
  }else if(item.order==='descending'){
    d=-1
  }else{
    let len=0
    state.showList.forEach(function(p1){
      if(p1[item.prop]){len++}
    })
    const mpid=state.showList[len>>1]
    state.showList.sort(function(p1,p2) {
      if(!p2[item.prop]){return -1}

      let num1
      let num2
      if(item.prop==='day'){
        num1=parseInt(p1[item.prop].replace(/-/g,''))
        num2=parseInt(p2[item.prop].replace(/-/g,''))
      }else{
        num1=Math.abs(parseFloat(p1[item.prop])||0-parseFloat(mpid[item.prop]))
        num2=Math.abs(parseFloat(p2[item.prop])||0-parseFloat(mpid[item.prop]))
      }
      if(num2>num1){
        return -1
      }else if(num2<num1){
        return 1
      }else{
        return 0
      }
    })
    getTableData();
    // initTable()
    return
  }
  state.showList.sort(function(p1,p2){
    if(!p2[item.prop]){return -1}

    let num1
    let num2
    if(item.prop==='day'){
      num1=parseInt(p1[item.prop].replace(/-/g,''))
      num2=parseInt(p2[item.prop].replace(/-/g,''))
    }else{
      num1=parseFloat(p1[item.prop])||0
      num2=parseFloat(p2[item.prop])||0
    }
    if(num2>num1){
      return d
    }else if(num2<num1){
      return -d
    }else{
      return 0
    }
  })
  getTableData();
}

const tItemClick=function (item,type){
window.open(`https://quote.eastmoney.com/qihuo/${item.code}.html`)
}
//点击搜索
const search= async(type)=>{

  Object.assign(routeQuery,state.filter)
  routeQuery.range_day=state.filter.range_day.join(',')
  routeQuery.pageIndex=1
  router.push({
    path:route.path,
    query:routeQuery
  })
}
// 分页改变
const onHandleSizeChange = (val: number) => {

  state.filter.pageSize = val;
  getTableData();
};
// 分页改变
const onHandleCurrentChange = (val: number) => {
  state.filter.pageIndex = val;
  getTableData();
};
let toggle=[]
// 表头
const changetNames = async (v) => {
  if(v[1]==='adUnitId'){
    if(!v[3]){
      state.tNames.forEach(function(v2){
        if(v2[4]===true){
          if(v2[3]===true){
            v2[3]=false
            toggle.push(v2)
          }
        }
      })
    }else{
      toggle.forEach(function(v2){
        v2[3]=true
      })
      toggle=[]
    }
  }
  state.tableData.tNames=state.tNames.filter(function (v){
    return v[3]
  })

};

//下载
const downTable= async ()=>{
  const option = {};
  option.fileName = `${state.filter.range_day.join('~')}~${state.filter.pkg}`;

  const sheetHeader=[]
  const sheetFilter=[]
  const sheetData=[]
  const columnWidths=[]
  state.tableData.tNames.forEach(function(arr){
    sheetHeader.push(arr[0])
    sheetFilter.push(arr[1])
  })
  state.showList.forEach(function (item){
    sheetData.push(item)
    columnWidths.push(5)
  })
  state.tjList.forEach(function(item){
    sheetData.push(item)
    columnWidths.push(5)
  })
  option.datas = [
    {
      sheetFilter: sheetFilter,
      sheetHeader: sheetHeader,
      sheetData: sheetData,
      columnWidths: columnWidths,
      sheetName: state.filter.pkg
    },
  ];
  const toExcel = new ExportJsonExcel(option); //new
  toExcel.saveExcel(); //保存
}
const updateTable=async()=>{
  state.tableData.loading=true
  await getData({
    pkg:"qihuo",
    type:'initList'
  })
  state.tableData.loading=false
}
const updatePrice=async()=>{
  state.tableData.loading=true
  await getData({
    pkg:"qihuo",
    type:'updatePrice'
  })
  state.tableData.loading=false
}
const updateChiCang=async()=>{
  state.tableData.loading=true
  await getData({
    pkg:"qihuo",
    type:'updateChiCang'
  })
  state.tableData.loading=false
}
const solveTable=async()=>{
  state.tableData.loading=true
  await getData({
      pkg:"qihuo",
      type:'solveList'
    })
  state.tableData.loading=false
}
// 页面加载时
onMounted(async () => {

//获取app包名

  const config = await getData({
    pkg:'qihuo',
    method:'getConfig'
  })
  if(!routeQuery.range_day){
    state.filter.range_day[0]=config.day
  }

  console.log(config)
  config.list.forEach(function (item,i){
    state.brandMap[item.brandName]=item.brandName

    if(state.filter.union_type==='all'||state.filter.union_type==item.brandName){
      state.appMap[item.title]=item.title
      if(state.filter.pkg==='all'||state.filter.pkg==item.title) {
        state.codeArrMap.push(item.code)
        if(state.filter.q===''||state.filter.q==item.code) {
          if(state.codeArr.indexOf(item.code)===-1){
            if(state.filter.isMaster=='1'){
              if(item.isMaster){
                state.codeNames.push(item.title)
                state.codeArr.push(item.code)
              }
            }else{
              state.codeNames.push(item.title)
              state.codeArr.push(item.code)
            }
          }

        }
      }
    }

  })
  await initTable()


});
</script>
